<template>
  <Box class="" :title="title" :animate="true" style="width: 33%;height: 100%;" v-if="!loading">
    <div style="display: flex; flex-direction: column; gap: 10px;" v-loading="loading" v-if="data && month">
      <div>
        <el-select v-model="month" placeholder="选择月份" style="width: 200px;float: right">
          <template #label="{ label, value }">
            <span style="font-weight: bold">月份: </span>
            <span>{{ value }}</span>
          </template>
          <el-option v-for=" item in Object.keys(data)" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
      <div style="display: flex; gap: 10px;">
        <el-progress type="dashboard"
          :percentage="scoreKey ? Math.floor(data[month][scoreKey] * 100) : computedScore * 100" :width="80">
          <template #default="{ percentage }">
            <span class="percentage-value">{{ percentage }}</span>
            <span class="percentage-label">风险值</span>
          </template>
        </el-progress>
        <InfoItem style="flex: 1" :title="store.schemas[scenario][h].split('$')[0]" :value="data[month][h]"
          v-for="h in highlights" :key="h">
        </InfoItem>
      </div>
      <div style="height: 140px;">
        <el-scrollbar height="100%" v-if="month != null">
          <el-descriptions :column="1" border style="background: none; overflow: hidden;">
            <!--注意判断store.schemas[scenario][k]，新增了score标签，在nebula中不存在-->
            <template v-for="[k, v] in (Object.entries(data[month] || {}))">
              <el-descriptions-item
                v-if="store.schemas[scenario][k] && store.schemas[scenario][k].split('$')[2] != 'archive'"
                :label="store.schemas[scenario][k].split('$')[0] + '：'" v-bind:key="k" label-align="right"
                label-class-name="label">
                <el-tag type="success"><el-text truncated style="max-width: 160px;">{{ v == -1 ? 0 : (v === null ? '不涉及'
                  : v)
                    }}</el-text></el-tag>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-scrollbar>
      </div>


      <Line style="height: 120px;"
        :data="Object.keys(data).sort().map(m => ({ '月份': m, '风险值': Math.floor(data[m][scoreKey] * 100), s: '风险值' }))">
      </Line>
    </div>
    <div v-else>
      <el-empty description="当前商户不涉及该场景" />
    </div>
  </Box>
</template>

<script lang="ts" setup>
import { computed, watch } from 'vue'
import Box from '../components/Box.vue'
import Box1 from '@/components/Box1.vue'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import InfoItem from './InfoItem.vue'
import { usePortraitStore } from '@/stores/portrait'
import { nebulaExec } from '@/utils/request'
import { groupBy, isEmpty, sum } from 'lodash'
import { useScoreStore } from '@/stores/score'
import { useMetaStore } from '@/stores/meta'
import { useSchemaStore } from '@/stores/schema'
import Line from './Line.vue'


const store = usePortraitStore()
const scoreStore = useScoreStore()
const metaStore = useMetaStore()
const schemaStore = useSchemaStore()

const props = defineProps(['title', 'highlights', 'scoreKey', 'scenario', 'id', 'labels'])
const loading = ref(true)
const data = ref(null)
const month = ref(null)
const computedScore = ref(0)

async function fetchData() {
  try {
    await schemaStore.load()
    const resp = await nebulaExec(`MATCH (c)-[e:${props.scenario}]->(c) WHERE id(c) == "${props.id}" return e`)
    // const resp = await nebulaExec(`FETCH PROP ON ${props.scenario} "${props.card}" -> "${props.card}"@${props.month} YIELD properties(edge)`)
    if (isEmpty(resp)) {
      loading.value = false
      scoreStore.mchtScores[props.title] = []
      metaStore.mchtLabels[props.title] = []
      return
    }
    const result = groupBy(resp.e, 'rank');
    Object.keys(result).forEach(k => {
      result[k] = result[k][0]['props']
    })
    // Object.keys(result).forEach(key => {
    //   const subGroup = groupBy(result[key], 'rank');
    //   Object.keys(subGroup).forEach(sk => {
    //     subGroup[sk] = subGroup[sk][0]
    //   })
    //   result[key] = subGroup;
    // });
    data.value = result
    console.log(result)

    month.value = resp.e[0].rank
    if (props.scenario == 'mchnt_label') {
      const comp_labels = ['case_num_mchnt_label', 'froz_num_mchnt_label', 'ill_num_mchnt_label']
      function computeScore(data: number[]) {
        if (sum(data) == 0) {
          return 0
        }
        return (70 + sum(data.map(d => d == 0 ? 0 : 1)) * 10) / 100
      }
      Object.keys(data.value).forEach(m => {
        const scores = comp_labels.map(l => data.value[m][l])
        // data.value = { ...data.value, score: computeScore(scores) }
        data.value[m]['score'] = computeScore(scores)
      })
      console.log(data)
      // const weiguiScores = comp_labels.map(l => sum(resp.e.map(e => e.props[l])))
      // computedScore.value = computeScore(result)
      scoreStore.mchtScores[props.title] = Object.values(data.value).map(v => v['score'])
    } else {
      scoreStore.mchtScores[props.title] = resp.e.map(e => e.props[props.scoreKey])
    }
  } finally {
    loading.value = false
  }
}

fetchData()

watch([month], () => {
  if (props.labels && month.value) {
    metaStore.mchtLabels[props.scenario] = Object.entries(data.value[month.value])
      .filter(([k, v]) => props.labels.includes(k) && v > 0)
      .map(([k, v]) => schemaStore.schemas[props.scenario][k].split('$')[0])
  }
})

// watch(
//   [() => props.id, () => props.month],
//   async (newVals, oldVals) => {
//     loading.value = true;
//     await fetchData();
//   }
// );

</script>

<style lang="css" scoped>
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 28px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 12px;
}
</style>
